package com.joinway.framework.admin.core.plugin.service;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.joinway.framework.admin.bean.domain.AdminRole;
import com.joinway.framework.admin.bean.domain.AdminRoleMenu;
import com.joinway.framework.admin.core.service.table.TableService;
import com.joinway.framework.bean.logging.annotation.InputLog;
import com.joinway.framework.bean.view.View;
import com.joinway.framework.core.utils.AppEnv;
import com.joinway.framework.data.jdbc.repository.TableRepository;
import com.joinway.framework.extension.utils.DataUtils;

@Service
public class AdminRoleTableService extends TableService {

	static final String MENU_IDS_KEY = "menuIds";
	
	@Autowired TableRepository repository;
	
	@Override
	public String getTableName() {
		return "adminRole";
	}


	@Transactional(rollbackFor=Throwable.class)
	@InputLog
	@Override
	public View save(String table, String idField, Map<String, String> params) throws Exception {
		AdminRole adminRole = super.getDomainEntity(params, AdminRole.class);
		adminRole.setAppId(AppEnv.getAppId());
		repository.save(adminRole);
		
		// remove existing map
		repository.delete("delete from admin_role_menu where role_id = ?", adminRole.getId());
		
		String[] ids = StringUtils.split(params.get(MENU_IDS_KEY), ",");
		if(ArrayUtils.isNotEmpty(ids)){
			for(String menuId : ids){
				AdminRoleMenu arm = new AdminRoleMenu();
				arm.setMenuId(DataUtils.convertToInt(menuId));
				arm.setRoleId(adminRole.getId());
				
				repository.save(arm);
			}
		}
		
		return new View();
	}


	@Override
	protected String getFindAllSql(String tableName) {
//		return "select * from " + tableName + " where app_id = '" + AppEnv.getAppId() + "' or length(trim(app_id)) = 0";
		return "select * from " + tableName + " where app_id = '" + AppEnv.getAppId() + "'";
	}


	@Override
	public int delete(String table, String idField, List<String> idValues) throws Exception {
		List<AdminRole> roles = repository.find(AdminRole.class, "select * from admin_role where id in (?)", StringUtils.join(idValues, ","));
		
		super.delete(table, idField, idValues);
		
		List<Integer> roleIds = new LinkedList<>();
		roles.stream().forEach(r -> roleIds.add(r.getId()));
		
		String sql = "delete from admin_role_menu where role_id in (?)";
		repository.delete(sql, StringUtils.join(roleIds, ","));
		
		return DataUtils.getSize(idValues);
	}


}
